import getGH from "../communicate/githubTree.js";
import { TOC, md } from "../all.js";
import { getContent } from "../communicate/GithubPart.js";
import renderMarkdown from "./markdown.js";

function renderTree(arr, lastPath) {
    let content = arr.files
        .map((i) => {
            return i.type === "directory" ? renderTree(i, i.path) : `<span data-path='${i.path}' class='tocList'>${i.name}</span>`;
        })
        .join("");
    return `<details open data-path='${lastPath}'><summary>${arr.name}</summary>${content}</details>`;
}

async function toc(user, repo, path) {
    let tree = await getGH(user, repo, path);

    TOC.innerHTML = renderTree(tree, path);
    [...TOC.querySelectorAll(".tocList")].forEach((i) => i.addEventListener("click", tocList));
}

async function tocList(e) {
    console.log(e.target.dataset.path);
    md.classList.toggle("animate__fadeInUp");
    setTimeout(() => {
        md.classList.add("animate__fadeInUp");
    }, 1);
    md.innerHTML = "";
    let text = await getContent(Setting.user, Setting.repo, e.target.dataset.path);
    renderMarkdown(text);
}
export default toc;
